﻿using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using qYun.ApiService.Services;
using qYun.Shared.Models;

namespace qYun.ApiService;

/// <summary>
/// 
/// </summary>
public class CustomInitializer : IHostedService, IDisposable
{
    private readonly ILogger<CustomInitializer> _logger;

    private readonly IServiceScopeFactory _scopeFactory;
    //private readonly IPlcService _plcService;
    private IGasService _gasService;
    private Timer _timer;
    private IHubContext<DataHub> _hubContext;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    public CustomInitializer(ILogger<CustomInitializer> logger,IServiceScopeFactory scopeFactory,IHubContext<DataHub> hubContext)
    {
        _logger = logger;
        //_plcService = plcService;
        _scopeFactory = scopeFactory;
        _hubContext = hubContext;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("应用启动时执行初始化逻辑...");
        // 执行数据库迁移、缓存预热等操作
        //开始任务调度
        using (var scope = _scopeFactory.CreateScope())
        {
            _gasService = scope.ServiceProvider.GetRequiredService<IGasService>();
        }

        _timer = new Timer(ExcuteTask, null, TimeSpan.Zero, TimeSpan.FromSeconds(20));
        return Task.CompletedTask;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("应用关闭时执行清理逻辑...");
        //取消定时器
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 
    /// </summary>
    public void Dispose()
    {
        // 释放资源
        _timer?.Dispose();
    }

    private void ExcuteTask(object state)
    {
        _logger.LogInformation("执行后台任务...");
        //
        var model = new GasModel()
        {
            CurrentStatus = 1,
            EnvironmentTemperature = new Random().Next(20,40),
            AtmosphericPressure = new Random().Next(20,40),
            DegassingTemperature = new Random().Next(20,40),
            DataAnalysisCount = new Random().Next(20,40),
            GasContent = new Random().Next(20,40),
            CreateTime = DateTime.Now
        };
        _gasService.InsertGasDataToDbAsync(model);
        //var data = JsonConvert.SerializeObject(model);
       // _hubContext.Clients.All.SendAsync("ReceiveData", model);
    }
}